package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;

import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    String prefix;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    ApArticleMapper apArticleMapper;

    /**
     * 生成文章静态页
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1 获取文章模板
            Template template = configuration.getTemplate("article.ftl");
            //2 准备数据
            HashMap<String, Object> map = new HashMap<>();
            // 存放文章数据
            map.put("article",apArticle);
            // 存放conten的map集合
            map.put("content", JSON.parseArray(content, Map.class));
            // 存放apuserId(通过作者id去作者表中查找用户id）
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId",apAuthor.getUserId());
            // 将数据信息转换成字符输出流 == 输入流
            StringWriter out = new StringWriter();
            template.process(map,out);
            ByteArrayInputStream in = new ByteArrayInputStream((out.toString()).getBytes());
            //3 把生成的页面上传minIO中
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", in);
            //4 修改ap_article表，保存静态url字段
            log.info("访问路为====> "+readPath+store);
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败。===>articleId:{} ====>原因：{}",apArticle.getId(),e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文章详情页生成失败");
        }
    }
}
